//
//  YJBTradeDetailViewController.m
//  YunJiaBaoFirst
//
//  Created by 腾云小白龍 on 16/7/29.
//  Copyright © 2016年 腾云小白龍. All rights reserved.
//

#import "YJBTradeDetailViewController.h"
#import "YJBDealRecodeSectionHeaderView.h"
#import "YJBTradeDetailBottomView.h"
#import "YJBTradeDealViewController.h"
#import "YJBSearchRecordViewController.h"
#import "YJBMyAccountViewController.h"
#import "YJBTradeExplainViewController.h"
#import "YJBTradeDetailHeaderView.h"
#import "YJBTradeBillView.h"
#import "YJBTradeDetailModel.h"
#import "YJBTradeDetailCell.h"
#import "YJBKlinePictureView.h"


@interface YJBTradeDetailViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>
@property (nonatomic, strong) UIScrollView * mainScrollView;
@property (nonatomic, strong) UITableView * mainTableView;
@property (nonatomic, assign) BOOL isMJRefresh;
@property (nonatomic, strong) YJBTradeDetailModel * tradeDetailModel;
@property (strong, nonatomic) NSMutableArray      * tradeDetailRecordArray;
@property (strong, nonatomic) YJBKlinePictureView *lineView; //曲线图
@property (strong, nonatomic) NSMutableArray *KTimeLineMinArr;
@property (strong, nonatomic) NSMutableArray *KLineDayArr;
@property (assign, nonatomic) CGFloat openPrice;
@property (strong, nonatomic) UIPageControl *pageCtrl;



@end

@implementation YJBTradeDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavigationItemWithTitle:@"模拟交易详情"];
    self.tradeDetailRecordArray = [NSMutableArray array];
    self.isMJRefresh = NO;
    [self initSubViews];
    [self initData];
}

-(void)viewWillDisappear:(BOOL)animated{
    if (self.isBackTradeMarket) {
        self.tabBarController.tabBar.hidden = NO;
    }
}

-(void)initSubViews{
    //scrollView
    UIScrollView *mainScrView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, SCREEN_HEIGHT - 20)];
    self.mainScrollView = mainScrView;
    mainScrView.showsVerticalScrollIndicator = NO;
    mainScrView.showsHorizontalScrollIndicator = NO;
    mainScrView.scrollEnabled = YES;
    mainScrView.delegate = self;
    mainScrView.contentSize = CGSizeMake(SCREEN_WIDTH*2,0 ); ///SCREEN_HEIGHT-20);
    mainScrView.pagingEnabled = YES;
    [self.view addSubview:mainScrView];
    
    //pageControlView
    UIPageControl *pageCtrl = [[UIPageControl alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, 20)];
    self.pageCtrl = pageCtrl;
    pageCtrl.numberOfPages = 2;
    pageCtrl.currentPageIndicatorTintColor = [UIColor redColor];
    pageCtrl.pageIndicatorTintColor = [UIColor lightGrayColor];
    pageCtrl.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:pageCtrl];
    
    //tableView
    self.mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 130) style:UITableViewStylePlain];
    self.mainTableView.delegate = self;
    self.mainTableView.dataSource = self;
    self.mainTableView.showsHorizontalScrollIndicator = NO;
    self.mainTableView.showsVerticalScrollIndicator = NO;
    self.mainTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    [mainScrView addSubview:self.mainTableView];
    self.mainTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.isMJRefresh= YES;
        [self initData];
    }];
    
    //lineView
    UIView *KlineView = [[UIView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 20 - 85)];
 
    [mainScrView addSubview:KlineView];
    
    YJBKlinePictureView *lineView = [[YJBKlinePictureView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, KlineView.height)];
    self.lineView = lineView;
    [lineView.hourButton addTarget:self action:@selector(showHourPicture:) forControlEvents:UIControlEventTouchUpInside];
    [lineView.dayButton addTarget:self action:@selector(showDayPicture:) forControlEvents:UIControlEventTouchUpInside];
    [KlineView addSubview:lineView];
    lineView.openPrice = self.openPrice;
    lineView.KLineDayArr = self.KLineDayArr;
    lineView.KTimeLineMinArr = self.KTimeLineMinArr;

    
    //添加底下按钮栏
    [self initBottomView];
}

#pragma mark -- 分时图
-(void)showHourPicture:(UIButton*)btn{
    [UIView animateWithDuration:1.0 animations:^{
        self.lineView.imageView.image = kImage(@"timeLine_sel");
        btn.titleLabel.font = [UIFont systemFontOfSize:18];
        self.lineView.dayButton.titleLabel.font = [UIFont systemFontOfSize:12];
        self.lineView.timeLineView.hidden = NO;
        self.lineView.klineView.hidden = YES;
    }];
    
}
#pragma mark -- k线图
-(void)showDayPicture:(UIButton*)btn{
    [UIView animateWithDuration:1.0 animations:^{
        self.lineView.imageView.image = kImage(@"dayLine_sel");
        btn.titleLabel.font = [UIFont systemFontOfSize:18];
        self.lineView.hourButton.titleLabel.font = [UIFont systemFontOfSize:12];
        self.lineView.klineView.hidden = NO;
        self.lineView.timeLineView.hidden = YES;
    }];
    
}


#pragma mark -- 获取数据
-(void)initData{
    NSString *url = [KMainURL stringByAppendingString:getTransportDealDetailURL];
    NSMutableDictionary *parma = [NSMutableDictionary dictionary];
    NSString *userToken        = [KUserDefault objectForKey:YJBUserToken];
    parma[@"userToken"]        =  @"000000000000000b/0b/570c839a128fe1006cadcd09";//userToken;
    [parma setObject :self.tradeID forKey:@"id"];
    
    [[HTAPI shareInstance] YJBActionWithGetRequset:url WithParameters:parma success:^(AFHTTPRequestOperation *operation, id responseObject) {

        if (_isMJRefresh) {
            [self.mainTableView.header endRefreshing];
            [SVProgressHUD showSuccessWithStatus:@"刷新成功"];
            [self performSelector:@selector(SVProgressHUDdismiss) withObject:nil afterDelay:1.0f];
            self.isMJRefresh = NO;
        }
        YJBLog(responseObject);
        [self performSelector:@selector(SVProgressHUDdismiss) withObject:nil afterDelay:1.0f];
        [self editingDataWithResponseObject:responseObject];
        [self.mainTableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSString *errorMessage) {
        YJBLog(errorMessage);
        if (_isMJRefresh) {
            [self.mainTableView.header endRefreshing];
            [SVProgressHUD showSuccessWithStatus:@"网络超时"];
            [self performSelector:@selector(SVProgressHUDdismiss) withObject:nil afterDelay:1.0f];
            self.isMJRefresh = NO;
        }
    }];
}

#pragma mark -- 处理数据
-(void)editingDataWithResponseObject:(id)responseObject{
    if ([responseObject isKindOfClass:[NSDictionary class]]) {
        YJBTradeDetailModel *tradeDetailModel = [MTLJSONAdapter modelOfClass:[YJBTradeDetailModel class] fromJSONDictionary:responseObject error:nil];
        
        self.tradeDetailModel = tradeDetailModel;
        //实时交易
        [self.tradeDetailRecordArray removeAllObjects];
        id contractsArr = [responseObject objectForKey:@"turnovers"];
        if ([contractsArr isKindOfClass:[NSArray class]]) {
            NSMutableArray *contArray = [NSMutableArray array];
            [contArray addObjectsFromArray:contractsArr];
            for (int i = 0; i<contArray.count; i ++) {
                NSDictionary *dict = contArray[i];
                YJBTradeDealRecodeModel *model = [MTLJSONAdapter modelOfClass:[YJBTradeDealRecodeModel class] fromJSONDictionary:dict error:nil];
                [self.tradeDetailRecordArray addObject:model];
            }
            
        }

        //曲线图
        if ([responseObject hasValueForKey:@"trendInMinutes"]) {
            self.KTimeLineMinArr = [responseObject objectForKey:@"trendInMinutes"];
        }
        
        if ([responseObject hasValueForKey:@"trendInDays"]) {
            self.KLineDayArr = [responseObject objectForKey:@"trendInDays"];
        }
        
        if ([responseObject hasValueForKey:@"openPrice"]) {
            self.openPrice = [[responseObject valueForKey:@"openPrice"] floatValue];
        }

    }
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else if (section == 2){
        return self.tradeDetailRecordArray.count;
    }else{
        return 3;
    }
}

#pragma mark -- tableView dataSource
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [[UITableViewCell alloc]init];
     cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.section == 0) {
        YJBTradeDetailHeaderView *view = [[YJBTradeDetailHeaderView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 135)];
        view.traDetailModel = self.tradeDetailModel;
        [cell.contentView addSubview:view];
    }
    
    if (indexPath.section == 1) {
           YJBTradeBillView *view = [[YJBTradeBillView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
        float riseScaleNum = [self.tradeDetailModel.riseScale floatValue];
        UIColor * color = BAD_MAIN_COLOR; // 绿色
        if (riseScaleNum >= 0) {
            color = MAIN_COLOR;
        }
        if (indexPath.row == 0) {
            if ([self.tradeDetailModel.sellQuantity integerValue] > 0) {
                NSString *price = [NSString stringWithFormat:@"%.2f元",[self.tradeDetailModel.sellPrice floatValue]];
                NSString *counts = [NSString stringWithFormat:@"%ld%@",[self.tradeDetailModel.sellQuantity integerValue],self.tradeDetailModel.unit];
                [view YJBTradeBillViewWithName:@"运力卖" withPrice:price withCounts:counts withColor:color];
            }else{
            [view YJBTradeBillViewWithName:@"" withPrice:@"暂无卖单" withCounts:@"" withColor:[UIColor grayColor]];
            }
        
        }else if (indexPath.row == 1){
            
             NSString *price = [NSString stringWithFormat:@"%.2f元",[self.tradeDetailModel.price floatValue]];
            
            [view YJBTradeBillViewWithName:@"现价" withPrice:price withCounts:nil withColor:color];

        }else{
            
            if ([self.tradeDetailModel.buyQuantity integerValue] > 0) {
                NSString *price = [NSString stringWithFormat:@"%.2f元",[self.tradeDetailModel.buyPrice floatValue]];
                NSString *counts= [NSString stringWithFormat:@"%ld%@",[self.tradeDetailModel.buyQuantity integerValue],self.tradeDetailModel.unit];
                [view YJBTradeBillViewWithName:@"运力买" withPrice:price withCounts:counts withColor:color];
            }else{
                [view YJBTradeBillViewWithName:@"" withPrice:@"暂无买单" withCounts:@"" withColor:[UIColor grayColor]];
            }
        

        }
           [cell.contentView addSubview:view];
    }
    
    if (indexPath.section == 2) {
        YJBTradeDetailCell * cell = [YJBTradeDetailCell cellWithTableView:tableView ];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.systemTime = [self.tradeDetailModel.currentTime integerValue];
        cell.tradeDealRecodeModel = self.tradeDetailRecordArray[indexPath.row];
        return cell;
    }
    return cell;
}



- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if(section == 1) {
        UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
        view.backgroundColor = DEFAULT_COLOR;
        
        UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, SCREEN_WIDTH - 20, 30)];
        label.textColor = [UIColor grayColor];
        label.font = [UIFont systemFontOfSize:14];
        label.text = @"挂单状况";
        [view addSubview:label];
//        [view setlayerBorder];
        return view;
    } else if(section == 2) {
        //实时交易情况
        YJBDealRecodeSectionHeaderView * view = [[YJBDealRecodeSectionHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 74)];
        view.backgroundColor = DEFAULT_COLOR;
        return view;
    }else{
        UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
        view.backgroundColor = DEFAULT_COLOR;
        
        UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, SCREEN_WIDTH - 20, 30)];
        label.textColor = [UIColor grayColor];
        label.font = [UIFont systemFontOfSize:14];
        NSString *tradeName = [NSString stringWithFormat:@"%@ %@",self.tradeName,self.tradeCode];
        label.text = tradeName;
        [view addSubview:label];
        
        return view;
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 2) {
        return 74;
    }else{
        return 30;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 135;
    }else{
        return 44;
    }
}

#pragma mark -- scrollView delegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    NSInteger page = self.mainScrollView.contentOffset.x / (SCREEN_WIDTH/2);
    self.pageCtrl.currentPage = page;
}

#pragma mark-- 初始化footerView
- (void)initBottomView {
    
    YJBTradeDetailBottomView * bottomView = [[YJBTradeDetailBottomView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 50, SCREEN_WIDTH, 85)];
    bottomView.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:bottomView];
    [bottomView.myCountButton addTarget:self action:@selector(myAccount) forControlEvents:UIControlEventTouchUpInside];
    
    [bottomView.openBtn addTarget:self action:@selector(contractDeal) forControlEvents:UIControlEventTouchUpInside];
    
    [bottomView.entrustBtn addTarget:self action:@selector(checkRecord) forControlEvents:UIControlEventTouchUpInside];
    
    [bottomView.tradeExplainBtn addTarget:self action:@selector(contractExplain) forControlEvents:UIControlEventTouchUpInside];
    
}

//我的账户
-(void)myAccount{

    YJBMyAccountViewController *vc = [[YJBMyAccountViewController alloc]init];

    [self.navigationController pushViewController:vc animated:YES];
}

//运力买卖
-(void)contractDeal{
    YJBTradeDealViewController *vc = [[YJBTradeDealViewController alloc]init];

    [self.navigationController pushViewController:vc animated:YES];
}

//记录查询
-(void)checkRecord{
    YJBSearchRecordViewController *vc = [[YJBSearchRecordViewController alloc]init];

    [self.navigationController pushViewController:vc animated:YES];
}

//合约详情
-(void)contractExplain{
    
    YJBTradeExplainViewController *vc = [[YJBTradeExplainViewController alloc]init];

    [self.navigationController pushViewController:vc animated:YES];
}




@end
